/*
 * Copyright (c) 2018, apexes.net. All rights reserved.
 *
 *         http://www.apexes.net
 *
 */
package net.apexes.commons.ormlite;

import java.sql.SQLException;

import android.content.AsyncTaskLoader;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Loader;
import android.database.ContentObserver;
import android.net.Uri;
import android.util.Log;

import com.j256.ormlite.android.apptools.OpenHelperManager;
import net.apexes.commons.lang.Checks;

/**
 * 使用ORMLite从数据库中查询记录的Loader实现。
 * 使用方法参见{@link android.content.CursorLoader}
 * 
 * @author <a href="mailto:hedyn@foxmail.com">HeDYn</a>
 *
 * @param <T>
 */
public abstract class OrmLiteLoader<T> extends AsyncTaskLoader<T> {
    
    private static final String TAG = OrmLiteLoader.class.getSimpleName();
    
    private final Uri mUri;
    
    private T mData;
    private ContentObserver mObserver;
    
    protected OrmLiteLoader(Context context, Uri uri) {
        super(context);
        Checks.verifyNotNull(uri, "uri");
        this.mUri = uri;
    }
    
    @Override
    public T loadInBackground() {
        try {
            DatabaseHelper databaseHelper = OpenHelperManager.getHelper(getContext(), getHelperClass());
            return query(databaseHelper);
        } catch (SQLException ex) {
            Log.w(TAG, "Query Error!", ex);
        } finally {
            OpenHelperManager.releaseHelper();
        }
        return null;
    }

    @Override
    public void deliverResult(T data) {
        mData = data;
        if (isStarted()) {
            super.deliverResult(data);
        }
    }
    
    @Override
    protected void onStartLoading() {
        if (mData != null) {
            deliverResult(mData);
        }
        
        if (mObserver == null) {
            mObserver = new ForceLoadContentObserver();
            ContentResolver resolver = getContext().getContentResolver();
            resolver.registerContentObserver(mUri, true, mObserver);
        }
        
        if (takeContentChanged() || mData == null) {
            forceLoad();
        }
    }
    
    @Override
    protected void onStopLoading() {
        cancelLoad();
    }
    
    @Override
    protected void onReset() {
        onStopLoading();
        
        if (mData != null) {
            mData = null;
        }
        
        if (mObserver != null) {
            ContentResolver resolver = getContext().getContentResolver();
            resolver.unregisterContentObserver(mObserver);
            mObserver = null;
        }
    }
    
    /**
     * 返回{@link SQLiteDatabaseHelper}实现类的类型
     * @return
     */
    protected abstract <E extends SQLiteDatabaseHelper> Class<E> getHelperClass();
        
    /**
     * 返回符合要求的记录，在回调的{@link android.app.LoaderManager.LoaderCallbacks#onLoadFinished(Loader, Object)}
     * 将传入此返回值。
     * @param databaseHelper
     * @return
     * @throws SQLException
     */
    protected abstract T query(DatabaseHelper databaseHelper) throws SQLException;

}
